package com.InetAddressDemo;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @Author weijingchen
 * @Date 2025/6/23 22:21
 * @Version 1.0.0
 */
public class Test03 {
    //接收端
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(10086);
        System.out.println("接收端启动成功");
        while (true){
            System.out.println("等待接收数据");
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
            //接收数据
            // 程序到这一步是阻塞的
            // 等待发送端发送数据，
            socket.receive(packet);
            byte[] data = packet.getData();
            String msg = new String(data, 0, packet.getLength());

            if ("bye".equalsIgnoreCase(msg) || "886".equals(msg)){
                System.out.println("程序结束："+msg);
                socket.close();
                break;
            }
            System.out.println("数据来源："+packet.getSocketAddress());
            System.out.println("主机名为"+packet.getAddress().getHostName());
            System.out.println("接收到数据："+msg);
        }
    }
}
